<!--
 * @Author: 涵崽
 * @Date: 2023-12-11 12:52:23
 * @email: 1045654@qq.com
 * @gitee: https://gitee.com/han-zai
 * @LastEditors: 涵崽
 * @LastEditTime: 2023-12-11 12:52:26
 * @Description: 微信：1045654
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <button id="startbutton">Take photo</button>

    <video id="video"></video>

    <canvas id="canvas"></canvas>

    <script>
      // 获取视频和画布元素
      const video = document.querySelector("#video");
      const canvas = document.querySelector("#canvas");
      const startButton = document.querySelector("#startbutton");

      // 启动摄像头
      async function startCamera() {
        const stream = await navigator.mediaDevices.getUserMedia({
          video: true,
        });
        video.srcObject = stream;
        video.play();
      }

      // 拍照

      function takePhoto() {
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        canvas.getContext("2d").drawImage(video, 0, 0);
      }

      // 启动摄像头
      startCamera();

      // 在按钮上绑定拍照事件
      startButton.addEventListener("click", takePhoto);
    </script>
  </body>
</html>
